﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolManager : MonoSingleton<PoolManager>
{
    void Awake()
    {
        DontDestroyOnLoad(this);
    }

    [System.Serializable]
    public class Pool
    {
        public string tag;
        public int size;
        public GameObject prefab;
        public Queue<GameObject> poolGos = new Queue<GameObject>();
        public Transform poolsParent;
    }

    [Header("需要初始化的池")]
    public List<Pool> pools;

    void Start()
    {
        Init();
    }

    void Init()
    {
        foreach (var pool in pools)
        {
            // 创建存储池的空物体
            GameObject singlePoolParent = new GameObject(pool.tag);
            singlePoolParent.transform.SetParent(transform);
            pool.poolsParent = singlePoolParent.transform;

            for (int i = 0; i < pool.size; i++)
            {
                GameObject go = GameObject.Instantiate(pool.prefab, pool.poolsParent);
                go.SetActive(false);
                pool.poolGos.Enqueue(go);
            }
        }
    }

    public GameObject Spawn(string tag, Vector3 pos, Quaternion rot, Transform parent = null)
    {
        GameObject go = null;
        foreach (var pool in pools)
        {
            if (pool.tag.Equals(tag))
            {
                if (pool.poolGos.Count > 0)
                {
                    go = pool.poolGos.Dequeue();
                    break;
                }
                else
                {
                    go = GameObject.Instantiate(pool.prefab);
                    break;
                }
            }
        }
        if (go != null)
        {
            go.SetActive(true);
            go.transform.position = pos;
            go.transform.rotation = rot;
            if (parent != null)
                go.transform.SetParent(parent);
            else
                go.transform.parent = null;
        }
        return go;
    }

    public void DeSpawn(string tag, GameObject go)
    {
        foreach (var pool in pools)
        {
            if (pool.tag.Equals(tag))
            {
                go.SetActive(false);
                go.transform.SetParent(pool.poolsParent);
                pool.poolGos.Enqueue(go);

                Trim();
            }
        }
    }

    void Trim()
    {
        foreach (var pool in pools)
        {
            if (pool.size < pool.poolGos.Count)
            {

                for (int i = 0; i < pool.poolGos.Count - pool.size; i++)
                {
                    GameObject go = pool.poolGos.Dequeue();
                    Destroy(go);
                }
            }

        }
    }

}